package com.pavlinic.codegen.usecases.createMainMethod;


import java.io.PrintWriter;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;

import com.pavlinic.codegen.FragmentGenerator;
import com.pavlinic.codegen.dsl.MethodInvocationGenerator;
import com.pavlinic.codegen.partialParser.PartialParser;

public class MainMethodGenerator implements FragmentGenerator {

  @SuppressWarnings("unchecked")
  @Override
  public ASTNode generateCode(AST ast) {
    final MethodDeclaration mainMethod = ast.newMethodDeclaration();
    mainMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    mainMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
    mainMethod.setName(ast.newSimpleName("main"));
   
    final SingleVariableDeclaration argument = ast.newSingleVariableDeclaration();
    argument.setType(ast.newArrayType(ast.newSimpleType(ast.newName("java.lang.String"))));
    argument.setName(ast.newSimpleName("args"));
    
    mainMethod.parameters().add(argument);
    
    final Block methodBody = ast.newBlock();
    mainMethod.setBody(methodBody);
    
    final QualifiedName sysout = (QualifiedName) new PartialParser().parseExpression("java.lang.System.out", ast);

    final MethodInvocationGenerator methodCallGen = new MethodInvocationGenerator(sysout);
    methodCallGen.callMethod(PrintWriter.class).println(methodCallGen.identifier("hello", String.class));
    
    methodBody.statements().add(ast.newExpressionStatement(methodCallGen.getMethodInvocation()));
    
    return mainMethod;
  }

}
